#include "String.h"

#define GetCharAsInt(Int) ((Int)-'0')

int S_ToInt(S_String *String)
{
	return (int)S_ToLong(String);
}


float S_ToFloat(S_String *String)
{
	return (float)S_ToDouble(String);
}

double S_ToDouble(S_String *String)
{
	double Result;
	Result = (double)S_ToLong(String);
	/* Find the position of the decimal place */
	int Position = S_FindFirstC(String, '.');
	if(Position == -1)
		return Result;
	/* Get the fractional part's string */
	S_String *FractionalPart = S_SubString(String, Position+1, String->Length-(Position+1));
	if(FractionalPart == NULL)
		return 0;
	S_Strip(FractionalPart);
	/* Work out how much to divide the number by */
	int Divide = (int)pow(10.0, S_GetStringLength(FractionalPart));
	/* Get the fractional part, make it fractional, and add it to the result */
	double NumericFractionalPart = S_ToLong(FractionalPart);
	NumericFractionalPart/=Divide;
	Result += NumericFractionalPart;
	S_FreeString(FractionalPart);
	return Result;
}

long S_ToLong(S_String *String)
{
	/* Create a new string and strip the whitespace (only leading and trailing) */
	S_String *TempString = S_NewStringSafe(String->String, String->Length);
	if(TempString == NULL)
		return 0;
	S_Strip(TempString);
	int Index = 0, Order, PointPos, IsNegative = 0, ApparentLength = 0, LengthTo = TempString->Length;
	long Result = 0;
	/* Check for signed-ness on the integer */
	if(TempString->String[0] == '-')
	{
		Index = 1;
		--ApparentLength;
		IsNegative = 1;
	}
	else if(TempString->String[0] == '+')
	{
		Index = 1;
		--ApparentLength;
	}
	/* Check if the string has a decimal point */
	if((PointPos = S_FindFirstC(TempString, '.')) != -1)
		LengthTo = PointPos;
	ApparentLength += LengthTo;
	/* Order is which 'column' the number is in */
	Order = (int)pow(10, ApparentLength - 1);
	while(Index < LengthTo)
	{
		if(isdigit(TempString->String[Index]))
		{
			long Diff = GetCharAsInt(TempString->String[Index])*Order;
			Result += (IsNegative ? -Diff : Diff);
			Order /= 10; /* Only reduce the order when a number is present.
							This allows for things like ',' and ' ' to be present in the strings */
		}
		++Index;
	}
	S_FreeString(TempString);
	return Result;
}
